package com.markor.tx.controllers;

import com.markor.tx.bean.Animal;
import com.markor.tx.bean.Family;
import com.markor.tx.bean.People;
import com.markor.tx.service.AnimalService;
import com.markor.tx.service.FamilyService;
import com.markor.tx.service.PeopleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author:zhangyanan
 * @Description: spring事务管理测试类
 * @Date:Crated in 8:58 2018/3/14
 * @Modified By:
 */
@RestController
@RequestMapping("/tx")
public class TransactionTest {

    @Autowired
    private PeopleService peopleService;

    @Autowired
    private FamilyService familyService;

    @Autowired
    private AnimalService animalService;

    @RequestMapping("/test")
    public String test() {
        return "test";
    }


    /**
     * 此方法测试spring单个事务的传播机制执行结果
     * 详见FamilyServiceImpl注释
     * 如有想了解，请逐个尝试
     */
    @RequestMapping("/addFamily")
    public String add(@RequestParam int num) {

        Family family = new Family();
        family.setPersonNum(num);

        familyService.insertByRequired(family);
//        familyService.insertByRequiresNew(family);
//        familyService.insertBySupports(family);
//        familyService.insertByNotSupported(family);
//        familyService.insertByNever(family);
//        familyService.insertByMandatory(family);
//        familyService.insertByNested(family);
        return "family添加成功";
    }


    /**
     * 当前peopleService未标注@Transactional
     * peopleServiceImpl执行insert方法，并调用familyService.insert*方法的事务处理机制
     *
     * @param num
     * @param name
     * @param age
     * @return
     */
    @RequestMapping("/add/noTransactional")
    public String noTransactional(@RequestParam int num, @RequestParam String name, @RequestParam Integer age) {

        People people = new People();
        people.setPeopleName(name);
        people.setAge(age);
        Family family = new Family();
        family.setPersonNum(num);

        peopleService.insert(people, family);

        return "测试peopleServiceImpl方法无事务，调用familyService.insert方法成功";
    }


    /**
     * animalService标注@Transactional
     * animalServiceImpl执行insert方法，并调用familyService.insert*方法的事务处理机制
     *
     * @param num
     * @param name
     * @return
     */
    @RequestMapping("/add/transactional")
    public String transactional(@RequestParam int num, @RequestParam String name) {

        Animal animal = new Animal();
        animal.setAnimalName(name);
        Family family = new Family();
        family.setPersonNum(num);

        animalService.insert(animal, family);

        return "测试animalServiceImpl方法存在事务，调用familyService.insert方法成功";
    }

}
